<template>
  <div class="bgc-back approval-detail-wrapper">
    <a-space>
      <a-button @click="handlerBack"> <a-icon type="left" />返回 </a-button>
    </a-space>

    <a-row class="approval-block" v-if="approval">
      <a-col :span="12">
        <div class="mb10">
          <span class="approval-block-top-title">{{ approval && approval.approName }}</span>
          <a-tag :color="getApprovalStatusColorBlue(approval && approval.status)">
            {{ getApprovalStatus(approval && approval.status) }}
          </a-tag>
        </div>
        <div class="mb10 approval-block-top-num">编号：{{ approval && approval.approNumber }}</div>
        <div class="mb10 approval-block-top-num">公司：{{ companyName }}</div>
        <div class="mb10 approval-block-top-num">类型：{{ approval && approval.approTypeCodeName }}</div>
      </a-col>
    </a-row>

    <a-row class="approval-block">
      <a-col :span="24" class="approval-block-title">审批流程</a-col>
      <a-col :span="24">
        <ApprovalProcess :approvalVal="approvalNodes" />
      </a-col>
    </a-row>
    <a-row class="approval-block">
      <a-col :span="24" class="approval-block-title">审批表单</a-col>
      <a-col :span="12" class="mt24">
        <ApprovalForm
          v-if="formVisible"
          ref="approvalForm"
          :dataSource="dataSource"
          :formFields="formFields"
          :formConfig="formConfig"
          class="approval-form"
        />
        <!-- <a-textarea v-model="remark"></a-textarea> -->
      </a-col>
    </a-row>
    <!-- salaryBill -->
    <a-row
      class="approval-block"
      v-if="this.approval && ['salaryBill', 'socBill', 'pfBill'].includes(this.approval.approTypeCode) && appRovalDet"
    >
      <a-col :span="24" class="approval-block-title">审批明细</a-col>
      <a-col :span="24">
        <approvalDetail @getappRovalDet="appRovalDet = false" :approvalId="approvalId"></approvalDetail>
      </a-col>
    </a-row>
    <a-row class="approval-block">
      <a-col :span="24" class="approval-block-title">审批记录</a-col>
      <a-col :span="24">
        <approvalTimeLine :approvalLog="approvalNodes"></approvalTimeLine>
      </a-col>
    </a-row>

    <div v-if="approval && approval.needAppro && userApprovalId && userApprovalId !== 'read'">
      <div style="height: 64px"></div>
      <div class="approval-block approvalBor">
        <a-button style="margin-right: 10px" @click="openModal('reject')" v-if="approval && approval.status == '1'">拒绝</a-button>
        <a-button class="detailBack" @click="openModal('agree')" v-if="approval && approval.status == '1'">同意</a-button>
      </div>
    </div>
    <!-- 弹出框 handlerAgree handlerReject-->
    <a-modal :title="Title" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="visible = false">
      <a-textarea :placeholder="placeholder" v-model="remark" :rows="4" />
    </a-modal>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { approvalDetailReq, approvalHandlerAgreeReq, approvalHandlerRejectReq } from "./api";
import ApprovalForm from "./components/approvalForm";
import ApprovalProcess from "./components/approvalProcess";
import approvalTimeLine from "./components/approvalTimeLine";
import approvalDetail from "./components/approvalDetail";
import { getApprovalStatus, getApprovalStatusColorBlue } from "./funcs";

export default {
  name: "",
  components: { ApprovalForm, ApprovalProcess, approvalTimeLine, approvalDetail },
  props: {},
  data() {
    return {
      appRovalDet: true,
      openState: "",
      confirmLoading: false,
      visible: false,
      placeholder: "请输入同意理由",
      Title: "审批同意",
      approval: null,
      approvalLogs: [],
      approvalNodes: [],
      userApproInfoList: [],
      dataSource: null,
      dynamicData: null,
      formFields: null,
      formConfig: null,
      formVisible: false,
      remark: ""
    };
  },
  computed: {
    ...mapState(["hr", "company"]),
    companyEmployeeList() {
      return this.company.companyEmployeeList;
    },
    companyDepartmentBaseList() {
      return this.company.companyDepartmentBaseList;
    },
    companyPositionBaseList() {
      return this.company.companyPositionBaseList;
    },
    companyName() {
      return this.hr.companyName;
    },
    approvalId() {
      return this.$route.params.approvalId;
    },
    userApprovalId() {
      return this.$route.params.userApprovalId;
    },
    dynamicValueMap() {
      return {
        applyUser: this.companyEmployeeList,
        oldDepartment: this.companyDepartmentBaseList,
        newDepartment: this.companyDepartmentBaseList,
        oldPosition: this.companyPositionBaseList,
        newPosition: this.companyPositionBaseList
      };
    },
    dynamicValueMapKeys() {
      return Object.keys(this.dynamicValueMap);
    },
    relationDataLoaded() {
      return this.companyEmployeeList.length > 0 && this.companyPositionBaseList.length > 0 && this.companyDepartmentBaseList.length > 0;
    }
  },
  watch: {
    relationDataLoaded: {
      handler(newVal) {
        if (newVal) {
          this.loadData();
        }
      },
      immediate: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    openModal(e) {
      this.openState = e;
      this.visible = true;
      this.remark = "";
      if (e === "agree") {
        this.Title = "审批同意";
        this.placeholder = "请输入同意理由";
      } else {
        this.Title = "驳回意见";
        this.placeholder = "请输入驳回理由";
      }
    },
    handleOk() {
      if (this.openState === "agree") {
        this.handlerAgree();
      } else {
        this.handlerReject();
      }
    },
    handlerBack() {
      this.$router.go(-1);
    },
    buildUserApproInfoList(values) {
      const keys = Object.keys(values);
      const userApproInfoList = this.userApproInfoList.filter((item) => item.settingType === "edit");
      keys.map((key) => {
        const idx = userApproInfoList.findIndex((item) => {
          return item.formId === key;
        });
        if (idx > -1) {
          userApproInfoList[idx]["value"] = values[key];
        }
      });
      return {
        userApproInfoList,
        remark: this.remark
      };
    },
    handlerAgree() {
      this.$refs["approvalForm"]
        .getData()
        .then((values) => {
          approvalHandlerAgreeReq(this.userApprovalId, this.buildUserApproInfoList(values)).then((res) => {
            // TODO 审批完成的提示，刷新数据
            this.visible = false;
            this.loadData();
          });
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.$message.error("数据未填写或格式错误");
        });
    },
    handlerReject() {
      this.$refs["approvalForm"]
        .getData()
        .then((values) => {
          approvalHandlerRejectReq(this.userApprovalId, this.buildUserApproInfoList(values)).then((res) => {
            // TODO 审批完成的提示，刷新数据
            this.visible = false;
            this.loadData();
          });
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.$message.error("数据未填写或格式错误");
        });
    },
    getApprovalStatusColorBlue,
    getApprovalStatus,
    loadData() {
      approvalDetailReq(this.approvalId)
        .then((res) => {
          // console.log(res);
          this.approval = res.data;
          this.approvalLogs = res.data.approLogList;
          this.approvalNodes = res.data.userApproNodeList;
          this.approvalNodes[0].approUserList = [{ userName: this.approval.userName, avatar: this.approval.userAvatar }];
          // 用于审批流程展示
          this.approvalNodes[0].userFlowApproverList = [
            {
              approverUserAvatar: this.approval.userAvatar,
              approverUserName: this.approval.userName,
              gmtCreate: this.approval.gmtCreate,
              approverOpinion: "发起审批",
              status: 2
            }
          ];
          this.userApproInfoList = res.data.userApproInfoList;
          this.buildForm(res.data.userApproInfoList);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    buildForm(list) {
      const formMap = {};
      const valueMap = {};
      const fieldKeys = [];
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        const field = JSON.parse(item.props);
        if (item.settingType === "read") {
          field.customize.disabled = true;
        }
        valueMap[field.model] = this.formatFormValues(item.value, item.widgetType, item.formCode);
        formMap[field.model] = field;
        if (["read", "edit"].includes(item.settingType)) {
          fieldKeys.push(field.model);
        }
      }
      this.dataSource = valueMap;
      this.formFields = formMap;
      this.formConfig = {
        fieldKeys: fieldKeys,
        customize: {
          layout: "vertical",
          labelAlign: "left"
        }
      };
      this.$nextTick(() => {
        this.formVisible = true;
      });
    },
    formatFormValues(value, type, model) {
      if (type === "switch") {
        return value === "true";
      } else if (type === "number") {
        return value ? Number(value) : value;
      } else {
        if (this.dynamicValueMapKeys.includes(model)) {
          const dataMap = this.dynamicValueMap[model];
          const theItem = dataMap.filter((item) => item.id === value);
          if (theItem.length > 0) {
            return theItem[0].name;
          } else {
            return value;
          }
        }
        return value;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.detailBack {
  background: var(--primary);
  color: #fff;
}
.approvalBor {
  text-align: right;
  box-shadow: 0px -4px 8px 0px rgba(0, 0, 0, 0.1);
  position: fixed;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 2;
  // width: 100%;
}
</style>
